<template>
  <div>
    <div class="row">
      <div class="col-md-6">
        <p>
          <button class="btn btn-white btn-default btn-round" @click="add1()">
            <i class="ace-icon fa fa-edit"></i>
            新增一级
          </button>
          &nbsp;
          <button class="btn btn-white btn-default btn-round" @click="all()">
            <i class="ace-icon fa fa-refresh"></i>
            刷新
          </button>
        </p>

        <table id="level1-table" class="table  table-bordered table-hover">
          <thead>
          <tr>
            <th>id</th>
            <th>名称</th>
            <th>顺序</th>
            <th>操作</th>
          </tr>
          </thead>

          <tbody>
          <tr v-for="category in level1"
              :key="category.id"
              :index="category.id"
              :class="{'active' : category.id === active.id}"
              @click="onClickLevel1(category)">
            <td>{{category.id}}</td>
            <td>{{category.name}}</td>
            <td>{{category.sort}}</td>

            <td>
              <div class="btn-group">
                <button class="btn btn-xs btn-info" @click="edit(category)">
                  <i class="ace-icon fa fa-pencil bigger-120"></i>
                </button>
                <button class="btn btn-xs btn-danger" @click="del(category.id)">
                  <i class="ace-icon fa fa-trash-o bigger-120"></i>
                </button>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <div class="col-md-6">
        <p>
          <button class="btn btn-white btn-default btn-round" @click="add2()">
            <i class="ace-icon fa fa-edit"></i>
            新增二级
          </button>
        </p>

        <table id="level2-table" class="table  table-bordered table-hover">
          <thead>
          <tr>
            <th>id</th>
            <th>名称</th>
            <th>顺序</th>
            <th>操作</th>
          </tr>
          </thead>

          <tbody>
          <tr v-for="category in level2"
              :key="category.id"
              :index="category.id">
            <td>{{category.id}}</td>
            <td>{{category.name}}</td>
            <td>{{category.sort}}</td>

            <td>
              <div class="btn-group">
                <button class="btn btn-xs btn-info" @click="edit(category)">
                  <i class="ace-icon fa fa-pencil bigger-120"></i>
                </button>
                <button class="btn btn-xs btn-danger" @click="del(category.id)">
                  <i class="ace-icon fa fa-trash-o bigger-120"></i>
                </button>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>


    <!-- Modal -->
    <div id="form-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">分类表单</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">父id</label>
                <div class="col-sm-10">
                    <p class="form-control-static">{{active.name || '无'}}</p>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">名称</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="category.name">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">顺序</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="category.sort">
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="save()">保存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    name: "business-category",
    data() {
      return {
        category: {
          id: null,
          parent: null,
          name: null,
          sort: null,
        },
        categorys: [],
        level1: [],
        level2: [],
        active: {}
      }
    },
    mounted() {
      let _this = this
      _this.all()
    },
    methods: {
      /**
       * 获取所有分类
       */
      all() {
        let _this = this

        Loading.show()

        _this.$axios.get(process.env.VUE_APP_SERVER + '/business/admin/category/all').then((resp) => {
          if (resp.data.success) {
            _this.categorys = resp.data.content

            // 将所有分类格式化成树形结构
            _this.level1 = []
            for (let i = 0; i < _this.categorys.length; i++) {
              let c = _this.categorys[i]
              if (c.parent === '00000000') {
                _this.level1.push(c)
                for (let j = 0; j < _this.categorys.length; j++) {
                  let child = _this.categorys[j]
                  if (child.parent === c.id) {
                    if (Tool.isEmpty(c.children)) {
                      c.children = []
                    }
                    c.children.push(child)
                  }
                }
              }
            }

            //  对当前一级分类中选中的表格出发一次点击事件, 以刷新二级菜单列表
            //  注意: 界面的渲染需要等vue绑定好变量后才做, 所有加延时100ms
            _this.level2 = []
            setTimeout(() => {
              $('tr.active').trigger('click')
            }, 100)

            Loading.hide()
          } else {
            Loading.hide()
          }
        })
      },

      /**
       * 添加一级分类（显示模态框）
       */
      add1() {
        let _this = this
        _this.active = {}
        _this.level2 = []
        _this.category = {
          parent: '00000000'
        }
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 添加二级分类（显示模态框）
       */
      add2() {
        let _this = this
        if (Tool.isEmpty(_this.active)) {
          Toast.warning('请先选择一级分类')
          return
        }
        _this.category = {
          parent: _this.active.id
        }
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 编辑分类（显示模态框）
       */
      edit(category) {
        let _this = this
        //  Object.assign(target, source)方法用于对象的合并，将源对象（source）的所有可枚举属性，复制到目标对象（target)
        Object.assign(_this.category, category)
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 保存分类
       */
      save() {
        let _this = this

        //  保存校验
        if (1 != 1
          || !Validator.require(_this.category.parent, "父id")
          || !Validator.require(_this.category.name, "名称")
          || !Validator.length(_this.category.name, "名称", 1, 50)
        ) {
          return;
        }

        _this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/category/save', _this.category).then((resp) => {
          if (resp.data.success) {
            //  关闭模态框
            $("#form-modal").modal('hide')
            //  刷新表格
            _this.all()
            Toast.success('保存成功！')
          } else {
            Toast.warning(resp.data.message)
          }
        })
      },

      /**
       * 删除分类（根据id）
       * @param id
       */
      del(id) {
        let _this = this
        Confirm.show('删除分类后不可恢复，是否确认删除？', () => {
          _this.$axios.delete(process.env.VUE_APP_SERVER + '/business/admin/category/delete/' + id).then((resp) => {
            if (resp.data.success) {
              //  刷新表格
              _this.all()
              Toast.success('删除成功！')
            }
          })
        })
      },

      /**
       * 点击父分类表格的行时, 显示其子分类
       * @param category
       */
      onClickLevel1(category) {
        let _this = this
        _this.active = category
        _this.level2 = category.children
      }
    }
  }
</script>

<style scoped>
  .active td {
    background-color: #d6e9c6 !important;
  }
</style>